package com.example.temp.controller;

import com.example.temp.common.Result;
import com.example.temp.entity.ClassEntity;
import com.example.temp.entity.Student;
import com.example.temp.mapper.ClassMapper;
import com.example.temp.mapper.StudentMapper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentMapper studentMapper;
    
    @Autowired
    private ClassMapper classMapper;

    // 添加学生
    @PostMapping("/insert")
    public Result insertStudent(@RequestBody Student student) {
        int result = studentMapper.insert(student);
        return Result.success(result);
    }

    // 更新学生信息
    @PutMapping("/update")
    public Result updateStudent(@RequestBody Student student) {
        int result = studentMapper.update(student);
        return Result.success(result);
    }

    // 分页查询学生
    @GetMapping("/showPage")
    public Result showPageStudent(@RequestParam String query, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        List<Student> students;
        int total;
        Map<String, Object> params = new HashMap<>();
        params.put("query", query);
        params.put("pageNum", (pageNum - 1) * pageSize);
        params.put("pageSize", pageSize);
        students = studentMapper.search(params);
        total = studentMapper.getTotal(query);
        return Result.success(total, students);
    }

    // 根据id查询学生信息
    @GetMapping("/query")
    public Result findTeacher(@RequestParam String studentID) {
        Student student = studentMapper.findByID(studentID);
        return Result.success(student);
    }

    // 删除学生
    @DeleteMapping("/{studentID}")
    public Result deleteStudent(@PathVariable("studentID") String studentID) {
        int result = studentMapper.deleteByID(studentID);
        return Result.success(result);
    }
    
    // 根据班级名称查询学生
//    @GetMapping("/findByClassName")
//    public Result findStudentsByClassName(@RequestParam String className,
//                                         @RequestParam(required = false) String query,
//                                         @RequestParam(required = false, defaultValue = "1") Integer pageNum,
//                                         @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
//        int offset = (pageNum - 1) * pageSize;
//        List<Student> students;
//        int total;
//        if (query != null && !query.isEmpty()) {
//            // 如果有查询参数，先查全部再内存过滤分页
//            students = studentMapper.findByClassName(className);
//            students = students.stream()
//                .filter(s -> s.getName().contains(query) || s.getStudentID().contains(query))
//                .collect(java.util.stream.Collectors.toList());
//            total = students.size();
//            int startIndex = offset;
//            int endIndex = Math.min(startIndex + pageSize, total);
//            if (startIndex < total) {
//                students = students.subList(startIndex, endIndex);
//            } else {
//                students = java.util.Collections.emptyList();
//            }
//        } else {
//            // 直接用数据库分页
//            students = studentMapper.findByClassNameWithPage(className, offset, pageSize);
//            total = studentMapper.countByClassName(className);
//        }
//        return Result.success(total, students);
//    }
    
    // 查找未分配班级的学生
    @GetMapping("/findNoClass")
    public Result findStudentsWithNoClass() {
        try {
            List<Student> students = studentMapper.findStudentsWithNoClass();
            return Result.success(students);
        } catch (Exception e) {
            return Result.fail("查询未分配班级的学生出错：" + e.getMessage());
        }
    }
    
    // 根据学号前缀搜索学生（未分配班级的学生）
    @GetMapping("/searchByStudentIdPrefix")
    public Result searchByStudentIdPrefix(@RequestParam String prefix) {
        try {
            // 获取所有未分配班级的学生
            List<Student> students = studentMapper.findStudentsWithNoClass();
            
            // 根据前缀过滤
            List<Student> filteredStudents = students.stream()
                .filter(s -> s.getStudentID() != null && s.getStudentID().startsWith(prefix))
                .collect(java.util.stream.Collectors.toList());
            
            return Result.success(filteredStudents);
        } catch (Exception e) {
            return Result.fail("根据学号前缀搜索学生失败：" + e.getMessage());
        }
    }
    
    // 更新学生班级
    @PutMapping("/updateClass")
    public Result updateStudentClass(@RequestBody Map<String, Object> params) {
        try {
            String studentID = (String) params.get("studentID");
            String className = (String) params.get("className");
            Integer classId = params.get("classId") != null ? Integer.parseInt(params.get("classId").toString()) : null;
            
            if (studentID == null || studentID.trim().isEmpty()) {
                return Result.fail("学生ID不能为空");
            }
            
            // 查询学生是否存在
            Student existingStudent = studentMapper.findByID(studentID);
            if (existingStudent == null) {
                return Result.fail("学生不存在");
            }
            
            // 先记录学生原班级ID
            Integer oldClassId = existingStudent.getClassId();
            
            // 如果没有传入classId但传入了className，根据className查找ClassId
            if (classId == null && className != null && !className.trim().isEmpty()) {
                ClassEntity classEntity = classMapper.queryClass(className);
                if (classEntity != null) {
                    classId = classEntity.getClassId();
                }
            }
            
            // 更新学生的班级
            int result;
            if (classId != null) {
                // 使用classId更新
                result = studentMapper.updateClassInfo(studentID, className, classId);
            } else {
                // 如果没有找到班级ID，则清空学生的班级信息
                result = studentMapper.updateClassName(studentID, className);
            }
            
            if (result > 0) {
                // 学生班级信息更新成功，接下来更新班级表的学生列表
                
                // 1. 如果学生有原班级，从原班级学生列表中移除该学生
                if (oldClassId != null) {
                    updateClassStudentList(oldClassId, studentID, false);
                }
                
                // 2. 如果学生有新班级，将学生添加到新班级学生列表
                if (classId != null) {
                    updateClassStudentList(classId, studentID, true);
                }
                
                return Result.success("更新学生班级成功");
            } else {
                return Result.fail("更新学生班级失败");
            }
        } catch (Exception e) {
            e.printStackTrace(); // 打印详细错误信息便于调试
            return Result.fail("更新学生班级出错：" + e.getMessage());
        }
    }
    
    /**
     * 更新班级学生列表
     * @param classId 班级ID
     * @param studentId 学生ID
     * @param isAdd true表示添加学生，false表示移除学生
     */
    private void updateClassStudentList(Integer classId, String studentId, boolean isAdd) {
        try {
            System.out.println("========== 更新班级学生列表 ==========");
            System.out.println("班级ID: " + classId + ", 学生ID: " + studentId + ", 操作: " + (isAdd ? "添加" : "移除"));
            
            // 查询班级信息
            ClassEntity classEntity = classMapper.findById(classId);
            if (classEntity == null) {
                System.out.println("错误: 未找到班级ID=" + classId);
                return;
            }
            
            // 获取班级学生列表
            String studentListStr = classEntity.getNumberOfStudents();
            System.out.println("原班级学生列表: " + studentListStr);
            
            List<String> studentList = new ArrayList<>();
            
            // 如果学生列表不为空，则解析JSON数组
            if (studentListStr != null && !studentListStr.trim().isEmpty()) {
                // 如果是正常的JSON数组格式（以[开头，以]结尾）
                if (studentListStr.startsWith("[") && studentListStr.endsWith("]")) {
                    studentListStr = studentListStr.substring(1, studentListStr.length() - 1);
                    if (!studentListStr.trim().isEmpty()) {
                        studentList = Arrays.stream(studentListStr.split(","))
                                .map(s -> s.trim().replace("\"", ""))
                                .collect(Collectors.<String>toList());
                    }
                } else {
                    // 如果只是一个值，直接加入
                    studentList.add(studentListStr.trim().replace("\"", ""));
                }
            }
            
            System.out.println("解析后的学生列表: " + studentList);
            
            // 根据操作类型处理学生列表
            if (isAdd) {
                // 添加学生，先检查是否已存在
                if (!studentList.contains(studentId)) {
                    studentList.add(studentId);
                    System.out.println("添加学生 " + studentId + " 到列表");
                } else {
                    System.out.println("学生 " + studentId + " 已存在于列表中，无需添加");
                }
            } else {
                // 移除学生
                boolean removed = studentList.remove(studentId);
                System.out.println(removed ? "从列表中移除学生 " + studentId : "学生 " + studentId + " 不在列表中，无法移除");
            }
            
            // 将学生列表转换回 JSON 格式
            StringBuilder jsonArray = new StringBuilder("[");
            for (int i = 0; i < studentList.size(); i++) {
                jsonArray.append("\"").append(studentList.get(i)).append("\"");
                if (i < studentList.size() - 1) {
                    jsonArray.append(",");
                }
            }
            jsonArray.append("]");
            
            String newStudentListJson = jsonArray.toString();
            System.out.println("新的学生列表JSON: " + newStudentListJson);
            
            // 更新班级学生列表
            int result = classMapper.updateStudentList(classId, newStudentListJson);
            System.out.println("更新班级学生列表结果: " + (result > 0 ? "成功" : "失败"));
            
            // 再次查询班级信息确认更新结果
            ClassEntity updatedClass = classMapper.findById(classId);
            if (updatedClass != null) {
                System.out.println("更新后的班级学生列表: " + updatedClass.getNumberOfStudents());
            }
            
            System.out.println("========== 更新班级学生列表完成 ==========\n");
        } catch (Exception e) {
            System.out.println("更新班级学生列表异常: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    // 批量获取学生信息
    @PostMapping("/batchInfo")
    public Result getBatchStudentInfo(@RequestBody Map<String, Object> params) {
        try {
            @SuppressWarnings("unchecked")
        List<String> studentIds = params.get("studentIds") instanceof List ? (List<String>) params.get("studentIds") : new ArrayList<>();
            Integer pageNum = params.get("pageNum") != null ? Integer.parseInt(params.get("pageNum").toString()) : 1;
            Integer pageSize = params.get("pageSize") != null ? Integer.parseInt(params.get("pageSize").toString()) : 10;
            
            if (studentIds == null || studentIds.isEmpty()) {
                return Result.fail("学生ID列表不能为空");
            }
            
            // 获取所有学生信息
            List<Student> students = new ArrayList<>();
            for (String studentId : studentIds) {
                Student student = studentMapper.findByID(studentId);
                if (student != null) {
                    students.add(student);
                }
            }
            
            // 计算总数
            int total = students.size();
            
            // 如果需要分页，进行简单的内存分页
            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize, total);
            
            // 确保索引有效
            List<Student> pagedStudents;
            if (startIndex < total) {
                pagedStudents = students.subList(startIndex, endIndex);
            } else {
                pagedStudents = java.util.Collections.emptyList(); // 空列表
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("total", total);
            result.put("list", pagedStudents);
            
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("批量获取学生信息出错：" + e.getMessage());
        }
    }

    // 按班级导出学生
    @GetMapping("/export")
    public void exportStudentsByClass(HttpServletResponse response, 
                                      @RequestParam(required = false) String className,
                                      @RequestParam(required = false) Integer classId) throws IOException {
        List<Student> students = new ArrayList<>();
        
        if (classId != null) {
            // 优先使用classId
            students = studentMapper.findByClassId(classId);
        } else if (className != null && !className.isEmpty()) {
            // 向后兼容，使用className
            students = studentMapper.findByClassName(className);
        }
        
        if (students.isEmpty()) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":400,\"msg\":\"没有学生数据\"}");
            return;
        }
        
        // 导出Excel
        String filename = "学生名单_" + (className != null ? className : "班级" + classId) + "_" + LocalDate.now() + ".xlsx";
        
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
        
        try (OutputStream os = response.getOutputStream()) {
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("学生名单");
            
            // 创建表头
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("学号");
            headerRow.createCell(1).setCellValue("姓名");
            headerRow.createCell(2).setCellValue("性别");
            headerRow.createCell(3).setCellValue("联系方式");
            headerRow.createCell(4).setCellValue("备注");
            headerRow.createCell(5).setCellValue("班级");
            
            // 填充数据
            int rowNum = 1;
            for (Student student : students) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(student.getStudentID());
                row.createCell(1).setCellValue(student.getName());
                row.createCell(2).setCellValue(student.getGender());
                row.createCell(3).setCellValue(student.getPhone());
                row.createCell(4).setCellValue(student.getNotes() != null ? student.getNotes() : "");
                row.createCell(5).setCellValue(student.getClassName() != null ? student.getClassName() : "");
            }
            
            // 自动调整列宽
            for (int i = 0; i < 6; i++) {
                sheet.autoSizeColumn(i);
            }
            
            workbook.write(os);
        } catch (Exception e) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":500,\"msg\":\"导出失败：" + e.getMessage() + "\"}");
        }
    }
}
